package AIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author fei.fang
 * @date 2021/8/24
 **/
public class AioServer {

    public static void main(String[] args) throws IOException {

        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8080));

        Attachment attachment = new Attachment();
        attachment.setServer(server);

        System.out.println("start");
        server.accept(attachment, new CompletionHandler<AsynchronousSocketChannel, Attachment>() {
            @Override
            public void completed(AsynchronousSocketChannel result, Attachment attachment) {
                try {
                    SocketAddress clientAddr = result.getRemoteAddress();
                    System.out.println("新连接" + clientAddr);

                    attachment.getServer().accept(attachment, this);

                    Attachment newAtt = new Attachment();
                    newAtt.setServer(server);
                    newAtt.setChannel(result);
                    newAtt.setReadMode(true);
                    newAtt.setBuffer(ByteBuffer.allocate(1024));

                    result.read(newAtt.getBuffer(), newAtt, new ChannelHandler());

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Attachment attachment) {
                System.out.println("accept failed");
            }
        });

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
